interface INewsItem {
  id: string;
  title: string;
  summary: string;
  thumbnail: string;
  createTime: string;
  categoryName: string;
  tagNames: string[];
}

interface IPageData {
  bannerList: Array<{
    id: number;
    imageUrl: string;
    title: string;
  }>;
  newsList: INewsItem[];
  categories: Array<{
    id: string;
    name: string;
  }>;
  currentCategory: string;
}

import { API } from '../../config/api.js';
import request from '../../utils/request';

Page<IPageData, any>({
  data: {
    bannerList: [
      {
        id: 'cat1',
        imageUrl: 'https://picsum.photos/800/400?random=1',
        title: '科技新闻',
      },
      {
        id: 'cat2',
        imageUrl: 'https://picsum.photos/800/400?random=2',
        title: '生活方式',
      },
      {
        id: 'cat3',
        imageUrl: 'https://picsum.photos/800/400?random=3',
        title: '健康生活',
      },
    ],
    newsList: [],
    categories: [
      {
        id: 'cat1',
        name: '技术',
        icon: 'https://picsum.photos/120/80?random=1',
      },
      {
        id: 'cat2',
        name: '健康',
        icon: 'https://picsum.photos/120/80?random=2',
      },
      {
        id: 'cat3',
        name: '生活',
        icon: 'https://picsum.photos/120/80?random=3',
      },
    ],
  },

  onLoad() {
    this.getNewsList();
  },

  goToList(e: any) {
    const { id, name } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/list/list?categoryId=${id}&categoryName=${name}`,
    });
  },

  goToDetail(e: any) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`,
    });
  },

  async getNewsList(categoryId?: string) {
    try {
      const params = {
        pageNum: 1,
        pageSize: 8,
        categoryId: categoryId || '',
      };

      const res = await request({
        data: params,
        url: API.news.list,
        method: 'POST',
        loading: true,
      });

      // 转换数据结构
      const newsData = (
        res as {
          data: {
            list: Array<{
              id: string;
              title: string;
              summary: string;
              thumbnail: string;
              createTime: string;
              categoryName: string;
              tagNames: string[];
            }>;
          };
        }
      ).data.list.map((item, index) => ({
        id: item.id,
        title: item.title,
        description: item.summary,
        imageUrl: `https://picsum.photos/200/150?random=${index + 10}`,
        createTime: item.createTime,
        category: item.categoryName,
        tags: item.tagNames,
      }));

      this.setData({
        newsList: newsData,
      });
    } catch (error) {
      console.error('获取新闻列表失败：', error);
    }
  },
});
